package com.iuie.ns.system.service.code.impl;

import java.io.Serializable;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.iuie.ns.frame.persistence.dao.IGenericDao;
import com.iuie.ns.frame.service.impl.BaseServiceImpl;
import com.iuie.ns.frame.web.dataset.vo.Page;
import com.iuie.ns.system.dao.code.ISysCodeInfoDao;
import com.iuie.ns.system.dao.code.ISysCodeTypeDao;
import com.iuie.ns.system.mapper.code.SysCodeInfoMapper;
import com.iuie.ns.system.mapper.code.SysCodeTypeMapper;
import com.iuie.ns.system.service.code.ISysCodeTypeService;
import com.iuie.ns.system.vo.code.SysCodeTypeVO;

@Service("codeTypeService")
public class SysCodeTypeServiceImpl extends BaseServiceImpl<SysCodeTypeVO> implements
		ISysCodeTypeService {
	
	@Resource
	private ISysCodeTypeDao codeTypeDao;

	@Resource
	private ISysCodeInfoDao codeInfoDao;
	
	@Resource
	private SysCodeTypeMapper codeTypeMapper;
	
	@Resource
	private SysCodeInfoMapper codeInfoMapper;
	
	@Override
	protected IGenericDao<SysCodeTypeVO, Serializable> getGenericDao() {
		return codeTypeDao;
	}
	
	@Override
	public void deleteById(Serializable id) {
		String typeId = (String) id;
		Session session = codeTypeDao.getCurrentSession();
		// 1. 先删除多的一方
		Query queryDeleteInfo = session.createQuery("delete from SysCodeInfoVO codeInfo where codeInfo.codeType.codeTypeId=:codeTypeId");
		queryDeleteInfo.setString("codeTypeId", typeId);
		queryDeleteInfo.executeUpdate();
		// 2. 再删除1的一方
		Query query = session.createQuery("delete from SysCodeTypeVO codeType where codeType.codeTypeId=:codeTypeId");
		query.setString("codeTypeId", typeId);
		query.executeUpdate();
	}

    @Override
    public List<SysCodeTypeVO> findCodeTypeByPage(SysCodeTypeVO codeType, Page page) {
        PageHelper.startPage(page.getPage(), page.getRows(), true);
        List<SysCodeTypeVO> list = codeTypeMapper.findCodeTypeByCondition(codeType);
        page.loadData(list);
        return list;
    }

    @Override
    public void removeCodeTypeById(String typeId) {
        Integer count = codeInfoMapper.getCodeInfoCountByTypeId(typeId);
        if (count == 0) {
            // 可以直接删除
            codeTypeMapper.deleteCodeTypeById(typeId);
        } else {
            // 状态置为-1，移除
            codeTypeMapper.removeCodeTypeById(typeId);
        }
    }

	@Override
	public void saveCodeType(SysCodeTypeVO codeType) {
		codeTypeDao.saveOrUpdate(codeType);
	}

	@Override
	public SysCodeTypeVO findCodeTypeById(String typeId) {
		return codeTypeMapper.findCodeTypeById(typeId);
	}


}
